package com.example.yyg.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.example.yyg.springframework.beans.BeansException;
import com.example.yyg.springframework.beans.PropertyValue;
import com.example.yyg.springframework.beans.PropertyValues;
import com.example.yyg.springframework.beans.factory.config.BeanDefinition;
import com.example.yyg.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.Objects;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{


    private InstantiationStrategy instantiationStrategy = new CglibInstantiationStategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object bean = null;
        try {
            if (args == null) {
                bean = instantiationStrategy.instantiate(beanDefinition, beanName, null, null);
            } else {
                Class beanClass = beanDefinition.getBeanClass();
                for (Constructor constructor:beanClass.getDeclaredConstructors()) {
                    if (constructor.getParameterCount() == args.length) {
                        bean = instantiationStrategy.instantiate(beanDefinition, beanName, constructor, args);
                        break;
                    }
                }
            }
            if (Objects.isNull(bean)) {
                throw new BeansException("no suitble constructor to create bean");
            }
            applyProperties(bean, beanName, beanDefinition);
            addSingleton(beanName, bean);
            return bean;
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
    }

    private void applyProperties(Object bean, String beanName, BeanDefinition beanDefinition) {
        if (Objects.isNull(bean)) {
            throw new BeansException("bean is null when applyProperties");
        }
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        if (propertyValues == null || propertyValues.isEmpty()) {
            return;
        }
        for (PropertyValue propertyValue:propertyValues.getPropertyValueList()) {
            if (propertyValue.getValue() instanceof BeanReference) {
                Object dependecyBean = getBean(propertyValue.getName());
                BeanUtil.setFieldValue(bean, propertyValue.getName(), dependecyBean);
            } else {
                BeanUtil.setFieldValue(bean, propertyValue.getName(), propertyValue.getValue());
            }
        }

    }


}
